% TraceDemo
% ___________________________________________________________________
%
% Draw a curve with the wheels
% _______________________________________________________________________
%
% Based on the MouseTraceDemo which ships with the PsychToolbox


try
    % Open up a window on the screen and clear it.
    whichScreen = max(Screen('Screens'));
    [theWindow,theRect] = Screen(whichScreen,'OpenWindow',0,[],[],2);
    
    traceLength = 100;
    
    midX = theRect(RectRight)/2;
    midY = theRect(RectBottom)/2;
    
    ShowCursor(0);
    Screen(theWindow,'DrawText','Initializing...', 50, 50, 255);
    Screen('Flip', theWindow);
    
    % initialize wheels
    wheels = RotaryEncoder('com12');
    
    % Loop and track the mouse, drawing the contour
    [theX,theY] = wheels.getXY();
    thePoints = [theX theY];
    
    % initial screen
    Screen(theWindow, 'DrawLine', 255, theX, theY, theX, theY);
    Screen('Flip', theWindow);
    
    while (1)
        % get x and y from the wheels
        [x, y] = wheels.getXY();
        
        % add the coordinates tho the track
        thePoints = [thePoints ; x y];
        
        % break if any key is pressed
        if KbCheck
            break;
        end
        
        % if the x or y value has changed...
        %if (x ~= theX | y ~= theY)
            % this loop actually draws the whole plot
            [numPoints, two]=size(thePoints);
            start = 1;
            if numPoints > traceLength
                start = numPoints - traceLength;
            end
            for i= start:numPoints-1
                Screen(theWindow, 'DrawLine', 128, thePoints(i, 1) + midX, thePoints(i, 2) + midY, thePoints(i + 1, 1) + midX, thePoints(i + 1, 2) + midY);
            end
            Screen('Flip', theWindow);
            theX = x; theY = y;
        %end
    end
    
    % Close up
    Screen(theWindow,'DrawText','Click mouse to finish',50,50,255);
    ShowCursor;
    wheels.close();
    Screen(theWindow,'Close');
    
    % Plot the contour in a Matlab figure
    plot(thePoints(:,1),theRect(RectBottom)-thePoints(:,2));
catch
    Screen('CloseAll');
    ShowCursor;
    psychrethrow(psychlasterror);
    wheels.close();
end %try..catch..
